package com.example.dingtalklogin.manager.dingtalk;

import com.example.dingtalklogin.common.util.SpringUtil;
import com.example.dingtalklogin.common.util.JacksonUtil;
import com.example.dingtalklogin.event.DingtalkTokenRefreshEvent;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.http.HttpStatus;

import java.io.BufferedReader;
import java.io.IOException;
import java.util.Objects;

/**
 * 钉钉新版api 错误返回非200-300状态，这里需要自定义解码器，解析token过期，发布刷新token事件
 * @author xuzhen97
 */
public class DingtalkTokenInvalidErrorDecoder extends ErrorDecoder.Default {
    @Override
    public Exception decode(String methodKey, Response response) {
        if(response.status() == HttpStatus.BAD_REQUEST.value()){
            try(BufferedReader bufferedReader = new BufferedReader(response.body().asReader())){
                StringBuffer buffer = new StringBuffer();
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    buffer.append(line);
                }
                ApiErrorResponse errorResponse = JacksonUtil.readValue(buffer.toString(), ApiErrorResponse.class);
                // 无效的access_token
                // 遇到返回无效token使用spring发布刷新token的事件
                if(Objects.equals(errorResponse.getCode(), "InvalidAuthentication")){
                    ApplicationEventPublisher publisher = SpringUtil.getEventPublisher();
                    DingtalkTokenRefreshEvent event = new DingtalkTokenRefreshEvent(this, errorResponse.getMessage());
                    publisher.publishEvent(event);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return super.decode(methodKey, response);
    }
}
